package red.lixiang.service.impl;

import red.lixiang.base.WXConfig;
import red.lixiang.dao.CartDAO;
import red.lixiang.dao.MemberDAO;
import red.lixiang.dao.OrderDAO;
import red.lixiang.dao.ProductDAO;
import red.lixiang.model.BaseInfo;
import red.lixiang.model.DTO.CashDTO;
import red.lixiang.model.Order;
import red.lixiang.model.Product;
import red.lixiang.service.OrderService;
import com.github.wxpay.sdk.WXPay;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDAO orderDAO;

    @Autowired
    private MemberDAO memberDAO;

    @Autowired
    private ProductDAO productDAO;

    @Autowired
    private CartDAO cartDAO;

    @Override
    @Transactional
    public BaseInfo submitCash(CashDTO cashDTO) {
        Order order = cashDTO.getOrder();

        if(order.getMemberId()!=0){
            //如果是本店会员
            if (order.getBalancePay().compareTo(0d)!=0) {
                //如果会员有用余额支付，则更新会员表
                memberDAO.memberRecharge(order.getBalancePay()*-1,order.getMemberId());
            }

            if(order.getScorePay().compareTo(0d)!=0){
                //如果有积分支付，则更新会员表的积分值
                Double scoreTotal = order.getScorePay()*3;
                memberDAO.memberGainScores(scoreTotal*-1,order.getMemberId());
            }

            //增加会员积分
            memberDAO.memberGainScores(order.getTotalPrice(),order.getMemberId());


        }

        //新建订单
        orderDAO.insertNewOrder(order);
        for (Product product : cashDTO.getProducts()) {
            if(product.getBarCode().length()==10){
                continue;
            }
            orderDAO.insertOrderProduct(order.getOrderId(),
                    product.getBarCode(),
                    product.getProductNum(),
                    product.getDiscount(),
                    product.getSaleType(),
                    product.getSalePrice());
            productDAO.updateProductNum(product.getBarCode(),product.getProductNum()*-1);
        }



        return new BaseInfo("0","成功插入",order);
    }

    @Override
    @Transactional
    public BaseInfo submitOrder(Order order, List<Product> products) {
        //新建订单
        orderDAO.insertNewOrder(order);
        for (Product product : products) {
            if(product.getBarCode().length()==10){
                continue;
            }
            orderDAO.insertOrderProduct(order.getOrderId(),
                    product.getBarCode(),
                    1,
                    0.28,
                    1,
                    product.getSalePrice());
        }
        return new BaseInfo("0","OK",order);
    }

    @Override
    public BaseInfo updateOrder(Order order) {
        orderDAO.updateOrder(order);
        return new BaseInfo("0","ok");
    }

    @Override
    public BaseInfo getOrderById(Integer id) {
        Order order = orderDAO.getOrderById(id);
        List<Product> products = orderDAO.getOrderProductByOrderId(id);
        Map<String , Object> map = new HashMap<>();
        map.put("orderInfo",order);
        map.put("products",products);
        return new BaseInfo("0","ok",map);
    }

    @Override
    public BaseInfo getOrderByType(Integer type,Integer memberId) {
        Map<String , Object> map = new HashMap<>();
        List<Order> orderList = orderDAO.getOrderByType(type,memberId);
        List<CashDTO> cashList = new ArrayList<>();
        for (Order order : orderList) {
            CashDTO cash  = new CashDTO();
            cash.setOrder(order);
            List<Product> products = orderDAO.getOrderProductByOrderId(order.getOrderId());
            cash.setProducts(products);
            cashList.add(cash);

        }
        map.put("orderList",cashList);
        map.put("type",type);

        return new BaseInfo("0","ok",map);
    }

    @Override
    public BaseInfo updateOrderStatus(Integer orderId, Integer status) {
        BaseInfo baseInfo = new BaseInfo("0","OK");
        Order order = new Order();
        order.setOrderId(orderId);
        order.setOrderStatus(status);
        orderDAO.updateOrder(order);
        return baseInfo;
    }

    @Override
    public BaseInfo finishOrder(Integer orderId,String openId) {
        Map<String , String  > data  = new HashMap<>();
        WXConfig config = new WXConfig();
        WXPay wxpay = new WXPay(config);
        data.put("out_trade_no",String.valueOf(orderId));
        try {
            Map<String , String > resp = wxpay.orderQuery(data);
            if(resp.get("trade_state").equals("SUCCESS")){
                //支付成功，去修改订单状态为已支付

                this.updateOrderStatus(orderId,6);
                BaseInfo baseInfo = this.getOrderById(orderId);
                //修改购物车，更改库存
                Map<String,Object> map = (Map<String, Object>) baseInfo.getObject();
                List<Product> products = (List<Product>) map.get("products");
                for (Product product : products) {
                    productDAO.updateProductNum(product.getBarCode(),-1);
                    cartDAO.deleteCartByOpenId(product.getBarCode(),openId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
